Inside Solaris logo
The Cobb Group This article is reprinted from the November 1996 issue of  Inside Solaris, a monthly publication of The Cobb Group.

Click for a FREE issue!


An introduction to Java applets and applications

By Probal Shome

One reason for all the hoopla regarding Java is that it holds great promise--the promise of machine independence. You're supposed to be able to write an applet on one of many platforms (from a PC running Windows 95 to an IBM mainframe running MVS) and instantly achieve cross-platform portability of the applet to all platforms on which the Java Virtual Machine (JVM) is implemented. In this article, we'll show you some of the basics of creating Java applets and applications. We assume that you have a working knowledge of C and object-oriented concepts, such as class, objects, methods, attributes, and inheritance.

We'll first build the traditional "Hello, World!" applet and present some variations. Next, we'll build a standalone Java application version of the "Hello, World!" program. Finally, we'll add the ability to display text that the user enters.

Installing Java

If you don't have Java installed, you'll have to download the Java Development Kit (the latest ver-sion at the time of this writing is v1.0.2) from http://java.sun.com/java.sun.com/products/JDK/index. html. Note to x86 users: Starting with JDK v1.0.2, Sun provides a version that runs on the Intel platform.

Quick introduction

Writing a Java applet is similar to using a third-party application toolbox with C++. Many of these provide a base class that manages the nuts-and-bolts details of an application, and you provide the code that makes the application do something interesting. Similarly, Java provides the base class Applet, which provides the basic details in telling the application how to open a window, redraw itself, and other general features. When you create a Java applet, you typically just ex-tend the Applet class. When you create a new class in Java, the new class must be in a file named ClassName.java, where ClassName is the name of the class you're creating. You can compile the ClassName.java file using javac to get the ClassName.class file, which holds the compiled JVM code. You can then run the code in ClassName.class with the Java in-terpreter, or if you have an HTML document that specifies it, you can view it with an HTML browser that supports Java, such as HotJava or Navigator. The JDK also comes with an applet viewer, which will execute Java applets specified in an HTML document.

The main difference between a Java applet and a Java application is that an applet needs to be run from a supporting program, such as a browser or the Java applet viewer program. A Java application may be run from the Java interpreter. An applet relies on the browser for sup-porting code, where an application is self-sufficient.

A short note about comments--Java recognizes three styles of comments: text enclosed by /* and */, text after // till the end of the line, and finally, text enclosed by /** and */, which has a special significance for the javadoc tool that generates documentation for Java applets. Since Java contains no preprocessor, we'll use /* and */ to block out chunks of code, which we would do in C using #if 0 ... #endif. Since /* and */ pairs do not nest, we'll leave them for block quotes and use // for line-at-a-time comments.

QUICK TIP: Note that Java, like C/C++, is case-sensitive. The words Class and class are different words. The Java tools (like the Java compiler javac) are also case-sensitive.

The HelloWorld applet

Let's start by writing a simple applet that displays the string "Hello, World!" Figure A shows the code for our first Java applet, HelloWorld.java. The first two statements import the Applet and Windowing classes that we're building upon for our example. You must include them, or the applet won't work. The Abstract Windowing Toolkit (AWT) provides the windowing user interface to our Java applet.


Figure A

 import java.applet.* ; // Remember the import statements
 import java.awt.* ;  // .. Abstract Windowing Toolkit 
 
 public class HelloWorld extends Applet { 
    // Display the applet using this method 
    public void paint(Graphics g) { 
     g.drawString ("Hello, World!", 50, 75 ); 
    } 
 } 

Our first Java applet simply displays a text string in the paint() method.


Next, we tell Java we're creating a new applet class named Hello-World by inheriting all useful methods (ways of doing things) from the generic Applet class. We redefine the way this applet displays itself on the screen by providing a new version of the paint() method. We use the drawString() method to display the text inside the applet's paint() method.

Using a text editor, we type the Java code above into a text file called HelloWorld.java. We then compile the code by typing

$ javac HelloWorld.java 

If the /java/bin directory isn't included in your PATH variable, you'll have to specify the complete path to javac, like this:

$ /java/bin/javac HelloWorld.java 

If javac compiles the code and finds no errors, it creates a file named HelloWorld.class in the current directory. In order to run the applet, we need to create an HTML document telling the brow-ser to run the applet. To do so, create the file HelloWorld.html in the current directory. Figure B shows the contents of the new HelloWorld.html file.


Figure B

 <HTML> 
 <APPLET code="HelloWorld.class" width=150 height=100> 
 </APPLET> 
 </HTML> 

This HTML document tells the browser to run the applet code found in HelloWorld.class in a 150x100 window.


If you open this HTML file in your Java-enabled Web browser, you should see your first Java applet! You can execute this applet with the appletviewer program like this:

$ appletviewer HelloWorld.html

Once you do so, you'll see the window shown in Figure C appear on your screen. For each new applet in this article, you'll have to create a new HTML file that looks like HelloWorld.html, changing only the name of the class in the APPLET tag. You can, of course, name the HTML files anything you choose.

Figure C

Here's the result of our HelloWorld applet.

 

HelloWorld: Where did the applet go?

Next, we'll change the foreground and background colors of the HelloWorld applet and examine an interesting technique for visually integrating Java applets into a Web page. While we could simply add some code to our HelloWorld.java program, we'll use this opportunity to show how easy it is to extend an existing class. So rather than modifying HelloWorld.java, we'll create a new file, called Color_HelloWorld.java, that extends Hello-World.java. Figure D contains the code for our Color_HelloWorld applet. As you can see, we merely redefine the init() method that the Applet class executes when it starts. You may be wondering (if you've not seen it in C++) what the keyword this denotes in the listing in Figure D. It's a self-reference that is implicitly passed to each method (operation) of the current object, i.e., this object--the object for which we're de-fining the method or operation. In this case, the keyword this translates into a reference to the Color_HelloWorld applet. And so, the foreground and background colors of this Color_ HelloWorld applet are set.


Figure D

import java.applet.* ; 
import java.awt.* ; 
public class Color_HelloWorld extends HelloWorld { 
   // Set the background and foreground colors 
   public void init() {
   // match your browser background 
   this.setBackground(Color.white);
    // whatever foreground color suits your fancy
   this.setForeground(Color.blue);
   } 
} 

The Color_HelloWorld applet modifies HelloWorld by changingthe foreground and background colors.


We use the setBackground() and the setForeground() methods to change the background and foreground colors of the Applet window. (For some color definitions, see the sidebar "Standard Java Colors" on page 4.) The java.awt.Component package defines the setBackground() and setFore-ground() methods. All GUI widgets, except menu components like menubar and menu-items, descend from the Component class. Thus, these two operations work on all these widgets, including applets.

The subclass-superclass relationship uses the ISA hierarchy model. In the ISA hierarchy model, a subclass is a (ISA) specialization of its superclass. For example, if you have the class hierarchy shown in Figure E, you can see that a Mango is a Fruit. So the Fruit class (collection of all fruits) is a superclass of the Mango class (collection of all mangoes). The Mango class is a subclass of the Fruit class.

 

Figure E

This hierarchy of edibles illustrates the ISA hierarchy model.


Similarly, an Applet ISA Panel (defined as a Container that's nested inside another Container) ISA Container ISA Component. This is the subclass-superclass chain that leads from an Applet up to a Component. This example gives you an idea of the hierarchical structure of the elements of the GUI interface. It extends to all aspects of Java, since it is an object-oriented language.

After this diversion into class hierarchies, let's get back to the Color_HelloWorld applet. Notice how we set the background color to white, so that it matches the browser's default background. Suddenly the text displayed inside the applet seems to be floating, since we can no longer see the boundaries of the applet within the Web page. This transparency effect is really striking for animated applets. (If your browser uses a default background other than white, you may want to change it to white for the duration of this demonstration.)

Building our first Java application

Now that we've built our HelloWorld applet and extended it, it's time to see how to create a standalone application. Let's build a stand-alone version that can be directly executed by the Java interpreter, outside the browser. To start, create the text file named HelloWorld-App.java, as shown in Figure F.


Figure F

// Note the absence of import packages
class HelloWorldApp { 
   // We must define main() which gets 
   // executed by default. 
   public static void main (String args[]) { 
       System.out.println ("Hello, World!" ) ; 
   } 
} 

HelloWorldApp.java is our first Java application.


For our application, we forgo the niceties of a windowing system. This Java application is much closer to the traditional "Hello, World!" application.

System.out is analogous to the standard output stream (STDOUT) used in C/C++. println() starts a new line after the text, just as if you used printf() in C and appended a newline (\n) to the format string. We compile the application using javac as before. How-ever, we run it differently, by executing the Java interpreter:

$ java HelloWorldApp 
Hello, World!

As you can see, the result is that the text "Hello, World!" gets printed. Here we've built a text-mode application, but this shouldn't lead you to conclude that Java applications are restricted to text mode. They can have graph-ical user interfaces as well. In fact, we'll build one in the next section.

Adding an input text field

We'll now build a Java application that allows you to type text in a field, which it then displays in a different pane. To do so, we implement a special kind of frame for our application. A frame is defined as an optionally resizable top-level application window. We'll define a subclass of the Frame class called TextFieldApp. Each such frame will contain a text field for the user to type in text and a text area for the text to be displayed. We create the frame, then add the text area and text field to it, after having customized them both for our purposes. We add them so that the text area is at the top of the frame, and the text field is at the bottom. Java will automatically do the layout for us. There are more complicated layout managers in Java, which allow the specification of elaborate layout constraints. These are useful for laying out windows containing several components.

Since this is a standalone Java application, we must define a main() method, in which we create, resize, and paint the frame. Finally, we need to write an event handler. In this case, the event handler is simpler than usual, since we're not concerned about mouse-clicks, keyboard events, or windowing events (like the window being moved). If we'd been interested in those events, we'd most probably have redefined the handle-Event() method. Since we're interested only in copying the text entered in the text field to the text area, we can take a shortcut and redefine the action() method to copy the text when necessary.

The code for our TextFieldApp.java pro-gram is shown in Figure G. Notice that we've left out, for the purposes of this exercise, elementary components of the window, such as a menu bar that would allow us to choose to quit the application. Now you can compile and run the TextFieldApp.java program using the commands

$ javac TextFieldApp.java
$ java TextFieldApp 

When you do so, you'll see the window shown in Figure H. To play with the application, type in some text in the lower text field, and press the [Enter] key. You should see the text in bigger letters echoed in the text area above. You'll have to kill this window manually, since we haven't implemented an OK button or a Quit menu item.


Figure G

import java.awt.* ; 


public class TextFieldApp extends Frame { 
    TextField textfield ; // For typing in text 
    TextArea textarea ; // and displaying it... 
    Font   textareafont ; 


    public TextFieldApp (String title) { 


    // Create a Frame with the title 
    super(title) ; 


    // Add text field and textarea 
    textfield = new TextField ("Enter text:", 40);
    textarea = new TextArea ("Displays happen here!", 
                 5, 40) ; 
    textarea.setEditable(false); // Don't allow user to 
                                 // modify it! 
    textarea.setBackground(Color.white) ; 
    textarea.setForeground(Color.black) ; 
    textfield.setForeground(Color.black) ; 


    // Set BIG font for display of textarea. 
    textareafont = new Font("Courier", Font.BOLD +
       Font.ITALIC, 36) ; 
    textarea.setFont(textareafont) ; 


    // Add these elements to the current frame. 
    this.add("North", textarea) ; 
    this.add("South", textfield); // very simple layout 


    } // end TextFieldApp() method 


    // All applications must have the main() method. 
    public static void main(String args[]) { 


      Frame f = new TextFieldApp ("First GUI
        ┬Application"); 


      f.pack(); // Resize to appropriately small size. 
      f.show(); 


    } // end main() method 


    // Handle text being typed in, and transfer it to 
    // the text area. 
    // The more generic method called handleEvent() 
    // can handle keyboard & mouse events and would 
    // be needed for more complex windows. 
    public boolean action (Event event, Object argument) { 


      // Text typed into text field ? 
      if (event.target == textfield) { 
        // Display text
        textarea.setText((String)argument + "\n" ) ; 
        return true; 
      }    
      else {  return false ; } 


    } // end action() method 


} // end TextFieldApp class 

This Java application copies any text entered into the text field to the text area.


Figure H

Here's what our Java application looks like when it first starts running.

 

Information resources

You can find many auxiliary sources of information about Java on the Internet. If you're interested in the cross-platform aspects of Java development, you can keep abreast of the JVM porting efforts for different platforms in the document http://java.sun.com/java.sun.com/Mail/external_lists.html. For a registry of many existing Java applets (along with the source code for many of them), you'll want to visit http://www.gamelan.com/. Also, check out http://java.sun.com/java.sun.com/applets/index.html for an index of many Java applets you can tinker with.

Don't forget to check your local bookstore for books on Java. Unless your bookstore is horribly out-of-date, there'll be about a trillion different books on Java. Be careful before you buy a Java book: Since Java is the current fad language, many books on it are junk.

Conclusion

We've shown you how to build simple Java applets and standalone applications. We also demonstrated how to extend an existing applet for which we had the Java source code. Finally, we explained how to create a Java application. Since the JDK is freely available on the Internet, and there are versions for both Sparc and Intel, you have no excuse not to download it and start playing with it! v Probal Shome is a Senior Technical Analyst with Oracle Worldwide Support. You can reach him at pshome@us.oracle.com.

 

[The Cobb Group Home Page]

Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.

Questions? Comments?